package com.jdd966.navigation;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author geyao
 * @date 2021/7/14
 * des:导航Tab布局
 */
public class NavigationTabList extends DirectionalLayout implements Component.ClickedListener {
    /**
     * Tab列表
     */
    private final List<NavigationTab> tabs;
    /**
     * 是否等比排列
     */
    private boolean isFixed = false;
    /**
     * Tab点击监听
     */
    private NavigationTabClickListener listener;

    public NavigationTabList(Context context) {
        this(context, null);
    }

    public NavigationTabList(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public NavigationTabList(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        this.tabs = new ArrayList<>();
    }


    /**
     * 设置Tab点击监听
     *
     * @param listener 监听
     */
    public void setOnTabClickListener(NavigationTabClickListener listener) {
        this.listener = listener;
    }

    /**
     * 添加Tab
     *
     * @param tab Tab
     */
    public void addTab(NavigationTab tab) {
        this.tabs.add(tab);
        this.addComponent(tab);
        tab.setClickedListener(this);
        refresh();
    }

    /**
     * 添加多个Tab
     *
     * @param tab Tab
     */
    public void addTab(NavigationTab... tab) {
        Collections.addAll(this.tabs, tab);
        for (NavigationTab navigationTab : tab) {
            this.addComponent(navigationTab);
            navigationTab.setClickedListener(this);
        }
        refresh();
    }

    /**
     * 设置是否等比排列
     *
     * @param isFixed 是否等比排列
     */
    public void setFixedMode(boolean isFixed) {
        this.isFixed = isFixed;
        refresh();
    }

    /**
     * 获取是否等比排列
     *
     * @return 是否等比排列
     */
    public boolean getFixedMode() {
        return this.isFixed;
    }

    /**
     * 刷新控件
     */
    public void refresh() {
        for (int i = 0; i < getChildCount(); i++) {
            Component component = getComponentAt(i);
            if (component instanceof NavigationTab) {
                ((NavigationTab) component).setWeight(isFixed ? 1f : 0f);
            }
        }
    }

    /**
     * 点击监听
     *
     * @param component 被点击的Component
     */
    @Override
    public void onClick(Component component) {
        for (int i = 0; i < this.tabs.size(); i++) {
            NavigationTab navigationTab = tabs.get(i);
            boolean isSame = navigationTab == component;
            navigationTab.setTabSelected(isSame);
            if (isSame) {
                if (this.listener == null) {
                    component.getClickedListener().onClick(component);
                    return;
                }
                this.listener.onTabClicked(i);
            }
        }
    }
}
